#!/bin/bash
#-----------------------------------------------------------
# Program   : die
# Location  : ~/lib/bfw/src
# Author    : Scott Smith <scott@bashify.com>
# Purpose   : Universal die() for bfw/bash scripts
# Copyright (c) 2008-2013 Scott Smith <scott@bashify.com>
#-----------------------------------------------------------

if [ -z "bfw_bash_framework" ]
then
  echo "error: bfw scripts cannot be run directly"
  exit 99
fi

#-----------------------------------------------------------

#:<
#= die [exitcode] [message]
#
# where: exitcode  0-255 or "" (null)
#        message   message text to output
#
# If exitcode is null, then the exitcode is zero (0).
#
# If message is null, then the default is used:
#
#     'SCRIPT' terminated with unknown reason
#
# If the message is '-', then no message is output.
#
# If only one parameter is given, then if it is number it is
# used for the errorcode and message is null; otherwise, the
# errorcode is null and the parameter is the message.
#
# This function Will call cleanup(), if it's defined, before
# exiting. This gives the calling script a way to ensure the
# proper cleanup of temp files, etc., before termination.
#
# Examples:
#
# ## exit with message, code 1
# die 1 "error: something bad happened"
#
# ## exit with default message, code 255
# die 255
#
# ## exit with no message, code 0
# die -
#
# ### exit with no message, code 1
# die 1 -
#:>

die()
{
    case "$1" in
    [0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])
        # found a number 0-255, set exit code and message
        ERR="$1"
        MSG="$2"
        ;;
    "")
        # no number or message, exit 0 and default message
        ERR=0
        MSG=""
        ;;
    *)
        # no number, but there was a message
        ERR=0
        MSG="$1"
        ;;
    esac

    # check for a cleanup() function, call it if it exists
    # but only if ERR > 0 -- NOTE THAT cleanup must NOT exit
    # but should return so this function can complete

    if (( ERR > 0 ))
    then
      [ "$(type -t cleanup)" = "function" ]  && cleanup
    fi

    # a '-' or '.' message supresses message output,
    # also note the use of echo -e to allow user's
    # to include \n an other escape characters

    case "$MSG" in
    -|.) : ;;
    "") echo "$PROG terminated with unknown reason" ;;
    *) echo -e "$MSG" ;;
    esac

    exit "$ERR"
}
declare -Ftx die

#-----------------------------------------------------------
#EOF(die)
